package com.estore.network;

import  com.estore.model.Product;
import com.estore.service.ProductService;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

/**
 * 电子商城服务器
 * 监听客户端连接，处理请求并返回数据
 */
public class EStoreServer {
    private ProductService productService;
    private ServerSocket serverSocket;
    private boolean isRunning;
    private static final int PORT = 8888;

    public EStoreServer(){
        this.productService = new ProductService();
        this.isRunning = false;
    }
    /**
     * 启动服务器
     */
    public void start(){
        try{
            serverSocket = new ServerSocket(PORT);
            isRunning = true;
            System.out.println("电子商城服务器启动成功，监听端口：" + PORT);
            System.out.println("等待客户端连接......");

            //循环接受客户端连接
            while (isRunning){
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接成功：" + clientSocket.getInetAddress());

                //为每个客户端创建新线程处理
                new Thread(new ClientHandler(clientSocket)).start();
            }
        }catch (IOException e){
            System.err.println("服务器启动失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 停止服务器
     */
    public void stop(){
        isRunning = false;
        try{
            if (serverSocket != null && !serverSocket.isClosed()){
                serverSocket.close();
            }
            System.out.println("服务器已停止");
        } catch (IOException e) {
            System.err.println("停止服务器时出错: " + e.getMessage());
        }
    }
    /**
     * 客户端处理器 - 内部类
     */
    private class ClientHandler implements Runnable {
        private Socket clientSocket;
        private ObjectInputStream inputStream;
        private ObjectOutputStream outputStream;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            try {
                // 创建输入输出流
                outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
                inputStream = new ObjectInputStream(clientSocket.getInputStream());

                System.out.println("客户端处理器已启动: " + clientSocket.getInetAddress());

                // 处理客户端请求
                while (!clientSocket.isClosed()) {
                    // 读取客户端请求
                    String request = (String) inputStream.readObject();
                    System.out.println("收到客户端请求: " + request);

                    // 处理请求
                    handleRequest(request);
                }
            } catch (EOFException e) {
                System.out.println("客户端断开连接: " + clientSocket.getInetAddress());
            } catch (IOException | ClassNotFoundException e) {
                System.err.println("处理客户端请求时出错: " + e.getMessage());
            } finally {
                closeConnection();
            }
        }

        /**
         * 处理客户端请求
         */
        private void handleRequest(String request) throws IOException {
            try {
                switch (request.toUpperCase()) {
                    case "GET_ALL_PRODUCTS":
                        handleGetAllProducts();
                        break;
                    case "GET_AVAILABLE_PRODUCTS":
                        handleGetAvailableProducts();
                        break;
                    case "GET_PRODUCT_BY_ID":
                        handleGetProductById();
                        break;
                    case "SEARCH_PRODUCTS_BY_NAME":
                        handleSearchProductsByName();
                        break;
                    case "SEARCH_PRODUCTS_BY_TAG":
                        handleSearchProductsByTag();
                        break;
                    case "ADD_PRODUCT":
                        handleAddProduct();
                        break;
                    case "UPDATE_PRODUCT":
                        handleUpdateProduct();
                        break;
                    case "DELETE_PRODUCT":
                        handleDeleteProduct();
                        break;
                    case "SAVE_DATA":
                        handleSaveData();
                        break;
                    case "BACKUP_DATA":
                        handleBackupData();
                        break;
                    case "EXIT":
                        closeConnection();
                        break;
                    default:
                        sendResponse("ERROR: 未知请求 - " + request);
                        break;
                }
            } catch (Exception e) {
                sendResponse("ERROR: 处理请求时出错 - " + e.getMessage());
            }
        }

        /**
         * 获取所有商品
         */
        private void handleGetAllProducts() throws IOException {
            List<Product> products = productService.getAllProducts();
            sendResponse(products);
            System.out.println("发送所有商品数据，数量: " + products.size());
        }

        /**
         * 获取有库存的商品
         */
        private void handleGetAvailableProducts() throws IOException {
            List<Product> products = productService.getAvailableProducts();
            sendResponse(products);
            System.out.println("发送有库存商品数据，数量: " + products.size());
        }

        /**
         * 根据ID获取商品
         */
        private void handleGetProductById() throws IOException, ClassNotFoundException {
            // 读取商品ID
            String productId = (String) inputStream.readObject();
            Product product = productService.findProductById(productId);

            if (product != null) {
                sendResponse(product);
                System.out.println("发送商品数据: " + product.getId());
            } else {
                sendResponse("ERROR: 商品不存在 - " + productId);
            }
        }

        /**
         * 根据名称搜索商品
         */
        private void handleSearchProductsByName() throws IOException, ClassNotFoundException {
            String keyword = (String) inputStream.readObject();
            List<Product> products = productService.searchProductsByName(keyword);
            sendResponse(products);
            System.out.println("根据名称搜索: '" + keyword + "'，结果数量: " + products.size());
        }

        /**
         * 根据标签搜索商品
         */
        private void handleSearchProductsByTag() throws IOException, ClassNotFoundException {
            String tag = (String) inputStream.readObject();
            List<Product> products = productService.searchProductsByTag(tag);
            sendResponse(products);
            System.out.println("根据标签搜索: '" + tag + "'，结果数量: " + products.size());
        }

        /**
         * 添加商品
         */
        private void handleAddProduct() throws IOException, ClassNotFoundException {
            Product product = (Product) inputStream.readObject();
            boolean success = productService.addProduct(product);

            if (success) {
                sendResponse("SUCCESS: 商品添加成功");
                System.out.println("添加新商品: " + product.getId());
            } else {
                sendResponse("ERROR: 商品添加失败，ID可能已存在");
            }
        }

        /**
         * 更新商品
         */
        private void handleUpdateProduct() throws IOException, ClassNotFoundException {
            Product product = (Product) inputStream.readObject();
            boolean success = productService.updateProduct(product);

            if (success) {
                sendResponse("SUCCESS: 商品更新成功");
                System.out.println("更新商品: " + product.getId());
            } else {
                sendResponse("ERROR: 商品更新失败，商品不存在");
            }
        }

        /**
         * 删除商品
         */
        private void handleDeleteProduct() throws IOException, ClassNotFoundException {
            String productId = (String) inputStream.readObject();
            Product deletedProduct = productService.deleteProduct(productId);

            if (deletedProduct != null) {
                sendResponse("SUCCESS: 商品删除成功");
                System.out.println("删除商品: " + productId);
            } else {
                sendResponse("ERROR: 商品删除失败，商品不存在");
            }
        }

        /**
         * 保存数据
         */
        private void handleSaveData() throws IOException {
            productService.saveData();
            sendResponse("SUCCESS: 数据保存成功");
            System.out.println("数据已保存");
        }

        /**
         * 备份数据
         */
        private void handleBackupData() throws IOException {
            boolean success = productService.backupData();

            if (success) {
                sendResponse("SUCCESS: 数据备份成功");
                System.out.println("数据备份完成");
            } else {
                sendResponse("ERROR: 数据备份失败");
            }
        }

        /**
         * 发送响应给客户端
         */
        private void sendResponse(Object response) throws IOException {
            outputStream.writeObject(response);
            outputStream.flush();
        }

        /**
         * 关闭连接
         */
        private void closeConnection() {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
                if (clientSocket != null && !clientSocket.isClosed()) {
                    clientSocket.close();
                }
                System.out.println("客户端连接已关闭: " +
                        (clientSocket != null ? clientSocket.getInetAddress() : "未知"));
            } catch (IOException e) {
                System.err.println("关闭连接时出错: " + e.getMessage());
            }
        }
    }

    /**
     * 服务器主方法
     */
    public static void main(String[] args) {
        EStoreServer server = new EStoreServer();

        // 添加关闭钩子，确保服务器正常关闭
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("\n正在关闭服务器...");
            server.stop();
        }));

        // 启动服务器
        server.start();
    }
}
